<template>
  <div class="stream-qa-container">
    <!-- 主内容区域 -->
    <div class="qa-content">
      <!-- 左侧历史记录 -->
      <div class="history-sidebar">
        <div class="sidebar-header">
          <h3>历史问答</h3>
          <el-button 
            type="primary" 
            :icon="Plus" 
            size="small" 
            @click="createNewSession"
          >
            新建对话
          </el-button>
        </div>

        <div class="history-list" v-if="historyList.length > 0">
          <div 
            v-for="item in historyList" 
            :key="item.id"
            class="history-item"
            :class="{ active: currentSessionId === item.id }"
            @click="loadHistory(item)"
          >
            <div class="history-content">
              <el-icon class="history-icon"><ChatDotRound /></el-icon>
              <div class="history-info">
                <div class="history-question">{{ item.question }}</div>
                <div class="history-time">{{ formatTime(item.created_at) }}</div>
              </div>
            </div>
            <el-icon 
              class="delete-icon" 
              @click.stop="deleteHistory(item.id)"
            >
              <Delete />
            </el-icon>
          </div>
        </div>

        <div v-else class="empty-history">
          <el-empty description="暂无历史记录" />
        </div>
      </div>

      <!-- 右侧对话区域 -->
      <div class="chat-area">
        <!-- 欢迎信息或消息列表 -->
        <div class="chat-messages" ref="chatMessagesRef">
          <!-- 欢迎信息 -->
          <div v-if="messages.length === 0" class="welcome-section">
            <div class="welcome-icon">
              <el-icon :size="60" color="#409eff"><Cpu /></el-icon>
            </div>
            <h2>智能流式问答助手</h2>
            <p>支持实时流式响应，逐字显示AI回答</p>
            
            <!-- 快速提问按钮 -->
            <div class="quick-questions">
              <el-button 
                v-for="q in quickQuestions" 
                :key="q"
                @click="askQuestion(q)"
                class="quick-btn"
              >
                {{ q }}
              </el-button>
            </div>
          </div>

          <!-- 消息列表 -->
          <div v-else class="messages-list">
            <div 
              v-for="(msg, index) in messages" 
              :key="index"
              class="message-group"
            >
              <!-- 用户问题 -->
              <div class="user-message">
                <div class="message-content">
                  <el-icon class="message-icon"><User /></el-icon>
                  <div class="message-bubble user-bubble">
                    {{ msg.question }}
                  </div>
                </div>
              </div>

              <!-- AI回答 -->
              <div class="ai-message">
                <div class="message-content">
                  <el-icon class="message-icon ai-icon"><Cpu /></el-icon>
                  <div class="message-bubble ai-bubble">
                    <div 
                      class="message-text"
                      v-html="formatAnswer(msg.answer)"
                    ></div>
                    <!-- 流式输入中的光标 -->
                    <span 
                      v-if="isStreaming && index === messages.length - 1" 
                      class="typing-cursor"
                    >|</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 加载动画 -->
            <div v-if="isLoading && !isStreaming" class="loading-message">
              <el-icon class="message-icon ai-icon"><Cpu /></el-icon>
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input">
          <el-input
            v-model="inputQuestion"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题... (Ctrl + Enter 发送)"
            @keydown.ctrl.enter="handleSend"
            :disabled="isLoading || isStreaming"
          />
          <div class="input-actions">
            <div class="input-tips">
              <el-icon><InfoFilled /></el-icon>
              <span>Ctrl + Enter 发送 | 支持流式响应</span>
            </div>
            <el-button
              type="primary"
              @click="handleSend"
              :loading="isLoading || isStreaming"
              :disabled="!inputQuestion.trim()"
            >
              {{ isStreaming ? '生成中...' : '发送' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Delete,
  ChatDotRound,
  User,
  Cpu,
  InfoFilled
} from '@element-plus/icons-vue'
import axios from 'axios'
import MarkdownIt from 'markdown-it'
import DOMPurify from 'dompurify'

// 初始化 Markdown 解析器
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  breaks: true
})

// 数据状态
const historyList = ref([])
const messages = ref([])
const inputQuestion = ref('')
const isLoading = ref(false)
const isStreaming = ref(false)
const currentSessionId = ref(null)
const chatMessagesRef = ref(null)

// 快速提问列表
const quickQuestions = [
  "什么是Vue.js的响应式原理？",
  "如何优化前端性能？",
  "Python与Java的区别是什么？",
  "医疗行业的数据隐私如何保护？"
]

// 页面加载时获取历史记录
onMounted(() => {
  fetchHistory()
})

// 创建新会话
const createNewSession = () => {
  messages.value = []
  currentSessionId.value = null
  inputQuestion.value = ''
}

// 加载历史记录
const loadHistory = (item) => {
  currentSessionId.value = item.id
  messages.value = [
    {
      question: item.question,
      answer: item.answer,
      timestamp: item.created_at
    }
  ]
  scrollToBottom()
}

// 删除历史记录
const deleteHistory = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    historyList.value = historyList.value.filter(item => item.id !== id)
    saveHistoryToLocal()
    
    if (currentSessionId.value === id) {
      createNewSession()
    }
    
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消删除:', error)
    }
  }
}

// 快速提问
const askQuestion = (question) => {
  inputQuestion.value = question
  handleSend()
}

// 发送问题（流式响应）
const handleSend = async () => {
  if (!inputQuestion.value.trim() || isLoading.value || isStreaming.value) return

  const question = inputQuestion.value.trim()
  
  // 添加用户问题到消息列表
  messages.value.push({
    question: question,
    answer: '',
    timestamp: new Date().toISOString()
  })

  inputQuestion.value = ''
  isLoading.value = true
  scrollToBottom()

  try {
    // 调用流式问答API
    await streamFetchAnswer(question)
  } catch (error) {
    console.error('发送问题失败:', error)
    ElMessage.error('网络错误，请稍后重试')
    messages.value[messages.value.length - 1].answer = '网络连接失败，请检查网络后重试'
  } finally {
    isLoading.value = false
    isStreaming.value = false
    scrollToBottom()
  }
}

// 流式获取答案（使用 fetch + ReadableStream）
const streamFetchAnswer = async (question) => {
  const messageIndex = messages.value.length - 1
  let fullAnswer = ''

  isLoading.value = false
  isStreaming.value = true

  try {
    console.log('🚀 开始流式请求:', question)
    
    const response = await fetch('http://localhost:8000/qa/stream/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        question: question
      })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    console.log('✅ 连接成功，开始接收数据...')

    // 获取响应的 ReadableStream
    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    
    let buffer = ''
    let chunkCount = 0

    while (true) {
      const { done, value } = await reader.read()
      
      if (done) {
        console.log('📦 流结束，共接收', chunkCount, '个数据块')
        break
      }

      // 解码数据块
      const chunk = decoder.decode(value, { stream: true })
      buffer += chunk
      
      console.log('📥 收到数据块:', chunk)
      
      // 处理可能包含多个 SSE 事件的数据
      const lines = buffer.split('\n')
      buffer = lines.pop() || '' // 保留不完整的行
      
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          try {
            const jsonStr = line.slice(6) // 移除 "data: " 前缀
            const data = JSON.parse(jsonStr)
            
            console.log('📨 解析数据:', data)
            
            // 兼容两种格式
            // 格式1: {"chunk": "文字", "done": false}
            // 格式2: {"type": "message", "content": "文字", "finished": false}
            
            let newContent = ''
            
            if (data.chunk) {
              // 格式1
              newContent = data.chunk
              chunkCount++
            } else if (data.content && data.type === 'message') {
              // 格式2
              newContent = data.content
              chunkCount++
            }
            
            if (newContent) {
              fullAnswer += newContent
              messages.value[messageIndex].answer = fullAnswer
              console.log('💬 累计内容长度:', fullAnswer.length)
              
              // 强制触发视图更新
              await nextTick()
              scrollToBottom()
              
              // 添加延迟，制造打字机效果（可调整延迟时间）
              await new Promise(resolve => setTimeout(resolve, 50))
            }
            
            // 检查是否完成（兼容两种格式）
            if (data.done || (data.type === 'complete' && data.finished)) {
              console.log('✅ 流式传输完成')
              // 流式传输完成
              isStreaming.value = false
              
              // 保存到历史记录
              const newHistory = {
                id: Date.now(),
                question: question,
                answer: fullAnswer,
                created_at: new Date().toISOString()
              }
              historyList.value.unshift(newHistory)
              saveHistoryToLocal()
              
              return
            }
          } catch (err) {
            console.error('❌ 解析JSON失败:', err, line)
          }
        }
      }
    }

    // 流结束
    isStreaming.value = false
    
    // 保存到历史记录
    if (fullAnswer) {
      const newHistory = {
        id: Date.now(),
        question: question,
        answer: fullAnswer,
        created_at: new Date().toISOString()
      }
      historyList.value.unshift(newHistory)
      saveHistoryToLocal()
    }
  } catch (error) {
    console.error('❌ 流式请求失败:', error)
    isStreaming.value = false
    
    // 降级到模拟流式响应
    ElMessage.warning('流式连接失败，使用模拟流式模式')
    await simulateStreamResponse(question, messageIndex)
  }
}

// 模拟流式响应（降级方案）
const simulateStreamResponse = async (question, messageIndex) => {
  try {
    // 调用普通API获取完整答案
    const response = await axios.post('http://localhost:8000/qa/single/', {
      question: question
    })

    if (response.data.code === 1) {
      const fullAnswer = response.data.data
      let currentText = ''
      
      // 模拟打字效果
      for (let i = 0; i < fullAnswer.length; i++) {
        currentText += fullAnswer[i]
        messages.value[messageIndex].answer = currentText
        
        // 控制打字速度（每个字符延迟）
        await new Promise(resolve => setTimeout(resolve, 30))
        
        // 每隔一段时间滚动到底部
        if (i % 5 === 0) {
          scrollToBottom()
        }
      }
      
      // 保存到历史记录
      const newHistory = {
        id: Date.now(),
        question: question,
        answer: fullAnswer,
        created_at: new Date().toISOString()
      }
      historyList.value.unshift(newHistory)
      saveHistoryToLocal()
    } else {
      ElMessage.error(response.data.message || '获取回答失败')
      messages.value[messageIndex].answer = '抱歉，获取回答时出错了'
    }
  } catch (error) {
    throw error
  }
}

// 获取历史记录（从localStorage加载）
const fetchHistory = async () => {
  try {
    const savedHistory = localStorage.getItem('stream_qa_history')
    if (savedHistory) {
      historyList.value = JSON.parse(savedHistory)
    }
  } catch (error) {
    console.error('获取历史记录失败:', error)
    historyList.value = []
  }
}

// 保存历史记录到localStorage
const saveHistoryToLocal = () => {
  try {
    localStorage.setItem('stream_qa_history', JSON.stringify(historyList.value))
  } catch (error) {
    console.error('保存历史记录失败:', error)
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now - date
  
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hourStr = String(date.getHours()).padStart(2, '0')
  const minuteStr = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hourStr}:${minuteStr}`
}

// 格式化答案（支持markdown和HTML）
const formatAnswer = (answer) => {
  if (!answer) return ''
  
  try {
    let html = md.render(answer)
    const cleanHtml = DOMPurify.sanitize(html, {
      ALLOWED_TAGS: [
        'p', 'br', 'strong', 'em', 'u', 'del', 's',
        'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
        'ul', 'ol', 'li',
        'blockquote', 'pre', 'code',
        'a', 'img',
        'table', 'thead', 'tbody', 'tr', 'th', 'td',
        'div', 'span'
      ],
      ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'class', 'id', 'target', 'rel']
    })
    
    return cleanHtml
  } catch (error) {
    console.error('格式化答案失败:', error)
    return answer
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/\n/g, '<br>')
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
    }
  })
}
</script>

<style scoped>
.stream-qa-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 49px);
  padding-top: 49px;
  background-color: #f0f2f5;
}

.qa-content {
  display: flex;
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  margin: 20px;
  overflow: hidden;
}

/* ==================== 左侧历史记录 ==================== */
.history-sidebar {
  width: 300px;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
  background-color: #f9fafc;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  background-color: #fff;
}

.sidebar-header h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.sidebar-header .el-button {
  width: 100%;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.history-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  margin-bottom: 8px;
  background-color: #fff;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid transparent;
}

.history-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.history-item.active {
  background-color: #ecf5ff;
  border-color: #409eff;
}

.history-content {
  display: flex;
  align-items: flex-start;
  flex: 1;
  overflow: hidden;
}

.history-icon {
  color: #409eff;
  margin-right: 10px;
  font-size: 18px;
  flex-shrink: 0;
}

.history-info {
  flex: 1;
  overflow: hidden;
}

.history-question {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.history-time {
  font-size: 12px;
  color: #999;
}

.delete-icon {
  color: #f56c6c;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
  font-size: 16px;
  flex-shrink: 0;
}

.history-item:hover .delete-icon {
  opacity: 1;
}

.delete-icon:hover {
  color: #f56c6c;
  transform: scale(1.2);
}

.empty-history {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

/* ==================== 右侧对话区域 ==================== */
.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

/* 欢迎区域 */
.welcome-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  text-align: center;
}

.welcome-icon {
  margin-bottom: 20px;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-10px); }
}

.welcome-section h2 {
  color: #303133;
  margin-bottom: 10px;
  font-size: 28px;
}

.welcome-section p {
  color: #909399;
  margin-bottom: 30px;
  font-size: 16px;
}

.quick-questions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-top: 20px;
}

.quick-btn {
  padding: 15px 20px;
  height: auto;
  white-space: normal;
  text-align: left;
}

/* 消息列表 */
.messages-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-group {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.user-message,
.ai-message {
  display: flex;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.message-content {
  display: flex;
  align-items: flex-start;
  max-width: 70%;
  gap: 10px;
}

.user-message .message-content {
  flex-direction: row-reverse;
}

.message-icon {
  font-size: 32px;
  flex-shrink: 0;
  margin-top: 5px;
}

.user-message .message-icon {
  color: #409eff;
}

.ai-icon {
  color: #67c23a;
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.6;
  word-break: break-word;
}

.user-bubble {
  background-color: #409eff;
  color: #fff;
  border-bottom-right-radius: 4px;
}

.ai-bubble {
  background-color: #f4f4f5;
  color: #303133;
  border-bottom-left-radius: 4px;
  position: relative;
}

.message-text {
  font-size: 14px;
}

/* 流式输入光标动画 */
.typing-cursor {
  display: inline-block;
  width: 2px;
  height: 1em;
  background-color: #409eff;
  margin-left: 2px;
  animation: blink 1s infinite;
  vertical-align: text-bottom;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

/* 加载动画 */
.loading-message {
  display: flex;
  align-items: center;
  gap: 10px;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 12px 16px;
  background-color: #f4f4f5;
  border-radius: 12px;
  border-bottom-left-radius: 4px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #909399;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% { transform: translateY(0); }
  30% { transform: translateY(-10px); }
}

/* ==================== 输入区域 ==================== */
.chat-input {
  padding: 20px;
  border-top: 1px solid #eee;
  background-color: #fafafa;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.input-tips {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #909399;
  font-size: 13px;
}

/* ==================== 滚动条样式 ==================== */
.history-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-thumb:hover,
.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #bbb;
}

/* ==================== Markdown 渲染样式 ==================== */
:deep(p) {
  margin: 0.8em 0;
  line-height: 1.6;
}

:deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
  margin: 1.2em 0 0.6em 0;
  font-weight: 600;
  line-height: 1.4;
  color: #303133;
}

:deep(h1) { font-size: 1.8em; border-bottom: 2px solid #e4e7ed; padding-bottom: 0.3em; }
:deep(h2) { font-size: 1.5em; border-bottom: 1px solid #e4e7ed; padding-bottom: 0.3em; }
:deep(h3) { font-size: 1.3em; }
:deep(h4) { font-size: 1.1em; }

:deep(strong), :deep(b) {
  font-weight: 600;
  color: #303133;
}

:deep(em), :deep(i) {
  font-style: italic;
  color: #606266;
}

:deep(code) {
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', 'Consolas', 'Monaco', monospace;
  font-size: 0.9em;
  color: #e74c3c;
  border: 1px solid #e4e7ed;
}

:deep(pre) {
  background: #282c34;
  color: #abb2bf;
  padding: 16px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 1em 0;
}

:deep(pre code) {
  background: transparent;
  padding: 0;
  border: none;
  color: inherit;
}

:deep(blockquote) {
  margin: 1em 0;
  padding: 12px 20px;
  border-left: 4px solid #409eff;
  background: #f4f4f5;
  color: #606266;
  border-radius: 0 4px 4px 0;
}

:deep(ul), :deep(ol) {
  margin: 0.8em 0;
  padding-left: 2em;
  line-height: 1.8;
}

:deep(ul) { list-style-type: disc; }
:deep(ol) { list-style-type: decimal; }
:deep(li) { margin: 0.3em 0; }

:deep(a) {
  color: #409eff;
  text-decoration: none;
}

:deep(a:hover) {
  color: #66b1ff;
  border-bottom: 1px solid #66b1ff;
}

:deep(table) {
  width: 100%;
  border-collapse: collapse;
  margin: 1em 0;
}

:deep(th), :deep(td) {
  padding: 12px 16px;
  border: 1px solid #e4e7ed;
}

:deep(th) {
  background: #f5f7fa;
  font-weight: 600;
}

:deep(tr:nth-child(even)) {
  background: #fafafa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .qa-content {
    flex-direction: column;
  }

  .history-sidebar {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid #eee;
  }

  .message-content {
    max-width: 85%;
  }

  .quick-questions {
    grid-template-columns: 1fr;
  }
}
</style>

